import { upload } from "./request";

/**
 * 将微信api转为promise
 * @param func
 * @param params
 * @returns {Promise}
 */
export function wxPromise(func, params) {
    return new Promise((resolve, reject) => {
        func({
            ...params,
            success: resolve,
            fail: reject
        })
    })
}

/**
 * 上传图片
 * @param params
 * @returns {Promise<any>}
 */
export function uploadImage(params = {}) {
    return wxPromise(wx.chooseImage, Object.assign(
        {
            count: 1
        },
        params
    )).then(res => {
        wx.showLoading({
            title: '正在上传中',
            mask: true
        })
        return Promise.allSettled(
            res.tempFilePaths
                .map(item => {
                    return upload(item, false)
                })
        )
    }).then(res => {
        wx.hideLoading()
        return res
            .filter(item => item.status === 'fulfilled')
            .map(item => item.value)
    })
}


/**
 * 数组扁平化
 * @param arr
 * @returns {any[]}
 */
export function flatten(arr) {
    return arr.reduce((result, item) => {
        return result.concat(Array.isArray(item) ? flatten(item) : item);
    }, []);
}

/**
 * 加法
 * @param num1
 * @param num2
 * @returns {number}
 */
export function add(num1, num2) {
    const num1Digits = (num1.toString().split('.')[1] || '').length;
    const num2Digits = (num2.toString().split('.')[1] || '').length;
    const baseNum = Math.pow(10, Math.max(num1Digits, num2Digits));
    return (num1 * baseNum + num2 * baseNum) / baseNum;
}
